package com.example.blew.demo.uitl;

import cn.hutool.core.util.StrUtil;
import com.example.blew.demo.model.ExcleReturn;

import java.io.FileWriter;
import java.io.IOException;
import java.util.*;

/**
 * <p>
 * TODO
 * </p>
 *
 * @author chaodong.zeng@pcitc.com
 * @since 2022/9/20
 */
public class ExcleUtil {


    // 分割汉字跟ip
    public ExcleReturn getAll(String str) {
        ExcleReturn excleReturn = new ExcleReturn();

        for (int i = 0; i < str.length(); i++) {

            if (str.charAt(i) >= 48 && str.charAt(i) <= 57) {
                excleReturn.setName(StrUtil.sub(str, 0, i));
                excleReturn.setIp(StrUtil.sub(str, i, str.length()));
                break;
            }
        }
        return excleReturn;
    }

    // 找到所有list里面相同的name，并添加入ip
    public HashMap categorize(List<ExcleReturn> list) {
        // map 存name 跟ip list
        HashMap<String, List<String>> categorizeMap = new HashMap<>();

        list.forEach(data -> {
            List<String> ipList = categorizeMap.get(data.getName());
            if (ipList == null || ipList.size() == 0) {
                ipList = new ArrayList<>();
                categorizeMap.put(data.getName(), ipList);
            }
            ipList.add(data.getIp() + "\n");
        });
        categorizeMap.toString();

        try {
            String line = System.getProperty("line.separator");
            StringBuffer str = new StringBuffer();
            FileWriter fw = new FileWriter("D:\\源62-64生产", true);
            Set set = categorizeMap.entrySet();
            Iterator iter = set.iterator();
            while (iter.hasNext()) {
                Map.Entry entry = (Map.Entry) iter.next();
                str.append(entry.getKey() + " : " + entry.getValue()).append(line);
            }
            fw.write(str.toString());
            fw.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


        return categorizeMap;
    }

    /**
     * @param list excle表传入的列表集合
     */
    public HashMap<String, List<ExcleReturn>> Classification(List<ExcleReturn> list) {
        HashMap<String, List<ExcleReturn>> categorizeMap = new HashMap<>();
        list.forEach(data -> {
            List<ExcleReturn> dataList = categorizeMap.get(data.getName());
            if (dataList == null || dataList.size() == 0) {
                dataList = new ArrayList<>();
                categorizeMap.put(data.getName(), dataList);
            }
            dataList.add(data);
        });
        return categorizeMap;
    }


}